#!/usr/bin/env bash

# 启用严格模式，遇错终止
set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
PROJECT_ROOT=$(dirname "$(dirname "$SCRIPT_DIR")")
echo "脚本所在目录：$SCRIPT_DIR"
echo "上上级目录（PROJECT_ROOT）：$PROJECT_ROOT"
IMAGE_REPO="registry.cn-hangzhou.aliyuncs.com/my_public_images"

# 默认服务名和 RPC 目录标志
SERVICE_NAME=${1:-user}        # 第一个参数：服务名
USE_RPC=${2:-"--use-rpc"}      # 第二个参数：是否使用 rpc 目录
DOCKERFILE_TEMP="${PROJECT_ROOT}/deploy/dockers/${SERVICE_NAME}.dockerfile"  # Dockerfile

echo "Building service: ${SERVICE_NAME}"
echo "RPC 目录模式: ${USE_RPC}"

# 清理旧二进制文件
BIN_DIR="${PROJECT_ROOT}/bin"
mkdir -p "${BIN_DIR}"
cd "${BIN_DIR}" || exit
echo "Cleaning ${SERVICE_NAME} binaries in $(pwd)..."
rm -f "${SERVICE_NAME}"

# 根据标志选择编译目录(自主选择是否使用rpc目录)
if [[ "$USE_RPC" == "--use-rpc" ]]; then
    COMPILE_DIR="${PROJECT_ROOT}/apps/${SERVICE_NAME}/rpc"
else
    COMPILE_DIR="${PROJECT_ROOT}/apps/${SERVICE_NAME}"
fi

cd "${COMPILE_DIR}" || {
    echo "错误: 目录不存在: ${COMPILE_DIR}"
    exit 1
}

echo "Compiling ${SERVICE_NAME} service from $(pwd)..."
# go mod tidy
# go clean -modcache -cache
go build -ldflags="-s -w -extldflags '-static'" -o "${BIN_DIR}/${SERVICE_NAME}" .

# 压缩二进制文件
#cd "${BIN_DIR}" || exit
#echo "Compressing ${SERVICE_NAME} binary with UPX..."
#if command -v upx &> /dev/null; then
#    upx -9 "${SERVICE_NAME}"
#else
#    echo "UPX not found, skipping compression"
#fi

# 动态生成 Dockerfile
echo "生成 Dockerfile 到 ${DOCKERFILE_TEMP}"
cat > "${DOCKERFILE_TEMP}" <<EOF
FROM alpine:3.18
WORKDIR /app
COPY bin/${SERVICE_NAME} /app/
COPY deploy/etcs/${SERVICE_NAME}.yaml /app/etc/
RUN chmod +x /app/${SERVICE_NAME}
CMD ["/app/${SERVICE_NAME}", "-f", "/app/etc/${SERVICE_NAME}.yaml"]
EOF

# 构建并推送 Docker 镜像
cd "${PROJECT_ROOT}" || exit
echo "Building Docker image for ${SERVICE_NAME} using dynamic Dockerfile..."
docker build \
  -f "${DOCKERFILE_TEMP}" \
  -t "${SERVICE_NAME}:latest" .

# 构建并推送 Docker 镜像
cd "${PROJECT_ROOT}" || exit
echo "Building Docker image for ${SERVICE_NAME}..."
docker build \
  -f "deploy/dockers/${SERVICE_NAME}.dockerfile" \
  -t "${SERVICE_NAME}:latest" .

echo "Tagging and pushing ${SERVICE_NAME} image to registry..."
docker tag "${SERVICE_NAME}:latest" "${IMAGE_REPO}/${SERVICE_NAME}:latest"
docker push "${IMAGE_REPO}/${SERVICE_NAME}:latest"

echo "${SERVICE_NAME} service built and deployed successfully!"

# 使用方式:
# bash service.sh user --use-rpc
# bash service.sh order --use-rpc
# bash service.sh api --no-rpc
